<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
    />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>21. 合并两个有序链表</title>
  </head>

  <body>
    <!-- start -->
    <div>https://leetcode.cn/problems/merge-two-sorted-lists/description/</div>
    <!-- end -->
  </body>

  <!-- js start -->
  <script type="text/javascript">
    /**
     * Definition for singly-linked list.
     * function ListNode(val, next) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.next = (next===undefined ? null : next)
     * }
     */
    /**
     * @param {ListNode} list1
     * @param {ListNode} list2
     * @return {ListNode}
     */
    var mergeTwoLists = function (list1, list2) {
      if (!list1 && !list2) return null;

      if (!list1) return list2;

      if (!list2) return list1;

      const firstNode = list1.val < list2.val ? list1 : list2;
      const prL1Node = null;

      while (list1 && list2) {
        if (list1.val >= list2.val) {
          prL1Node.next = list2;
          prL1Node = list2;
          list2 = list2.next;

          let valTemp = list1.val;
        } else {
          prL1Node = list1;
          list1 = list1.next;
        }
      }

      return firstNode;
    };

    function ListNode(val, next) {
      this.val = val === undefined ? 0 : val;
      this.next = next === undefined ? null : next;
    }

    /*******************************************************************************
     * 以下为测试代码
     ******************************************************************************/
    const l1 = [1, 2, 4];
    const l2 = [1, 3, 4];

    // class ListNode {
    //   constructor(val) {
    //     this.val = val;
    //     this.next = null;
    //   }
    // }

    showNode(mergeTwoLists(list2Node(l1), list2Node(l2)));

    function showNode(firstNode) {
      const list = [];

      if (!firstNode) return console.log(list);

      while (firstNode) {
        list.push(firstNode.val);
        firstNode = firstNode.next;
      }

      return console.log(list);
    }

    function list2Node(arr) {
      if (!arr) return null;

      const firstNode = new ListNode(arr[0]);
      let node = firstNode;
      for (let i = 1; i < arr.length; i++) {
        node.next = new ListNode(arr[i]);
        node = node.next;
      }

      return firstNode;
    }
  </script>
</html>
